package com.lemon.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.PageResult;
import com.lemon.domain.Sku;
import com.lemon.domain.Spu;
import com.lemon.domain.Supplier;
import com.lemon.domain.dto.SkuDto;
import com.lemon.domain.pageParam.SkuPageParam;
import com.lemon.mapper.SkuMapper;
import com.lemon.mapper.SpuMapper;
import com.lemon.mapper.SupplierMapper;
import com.lemon.service.SkuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private final SpuMapper spuMapper;
    private final SkuMapper skuMapper;
    private final SupplierMapper supplierMapper;

    @Override
    public PageResult getAll(SkuPageParam skuPageParam) {
        PageHelper.startPage(skuPageParam.getPage(),skuPageParam.getPageSize());
        List<Spu> spuList = spuMapper.selectList(Wrappers.<Spu>lambdaQuery()
        .like(ObjectUtils.isNotEmpty(skuPageParam.getTitle()),Spu::getTitle,skuPageParam.getTitle()));
        List<SkuDto> skuDtoList = new ArrayList<>();
        spuList.forEach(spu -> {
            Supplier supplier = supplierMapper.selectById(spu.getSupplierId());
            List<Sku> skuList = skuMapper.selectList(Wrappers.<Sku>lambdaQuery().like(ObjectUtils.isNotEmpty(skuPageParam.getCode()), Sku::getCode, skuPageParam.getCode()).eq(Sku::getSpuId, spu.getId()));
            skuList.forEach(sku -> {
                SkuDto skuDto =new SkuDto();
                skuDto.setId(sku.getId());
                skuDto.setCode(sku.getCode());
                skuDto.setTitle(spu.getTitle());
                skuDto.setSupplierId(spu.getSupplierId());
                skuDto.setSupplierName(supplier.getSupplierName());
                skuDtoList.add(skuDto);
            });
        });
        // 正确创建 Page 对象
        Page<SkuDto> page = new Page<>();
        page.addAll(skuDtoList);
        // 注意：这里需要设置分页信息，可能需要额外查询总数
        return new PageResult(page.getTotal(), page.getResult());
    }
}
